package ali.timer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * User: aliolci
 * Date: 25/06/11
 * Time: 16:57
 * To change this template use File | Settings | File Templates.
 */
public class Timer{
    private List<TimerListener> listeners = new ArrayList<TimerListener>();
    private boolean isRunning=true;
    private Thread thread = new Thread(run());
    public Timer(TimerListener listener){
        addListener(listener);
    }
    public void addListener(TimerListener listener){
        listeners.add(listener);
    }

    public void removeListener(TimerListener listener){
        listeners.remove(listener);
    }
    public void clearListeners(){
        listeners.clear();
    }
    public void stop(){
        isRunning = false;
    }
    public void start(){
        thread.start();
        isRunning = true;
    }

    private Runnable run() {
        return new Runnable() {
            public void run() {
                start_allListeners();
                while (isRunning){
                    tick_allListeners();
                    sleep(4);
                }
                stop_allListeners();
            }
        };
    }

    private void sleep(int interval) {
        try {
            Thread.sleep(interval);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void stop_allListeners() {
        Iterator<TimerListener> iterator = listeners.iterator();;
        while (iterator.hasNext()){
            iterator.next().stop();
        }
    }

    private void start_allListeners() {
        Iterator<TimerListener> iterator = listeners.iterator();;
        while (iterator.hasNext()){
            iterator.next().start();
        }
    }

    private void tick_allListeners() {
        Iterator<TimerListener> iterator = listeners.iterator();;
        while (iterator.hasNext()){
            iterator.next().tick();
        }
    }
}
